export function getSelection(editor: any) {
  const selection = window.getSelection();
  if (selection && !selection.isCollapsed) {
    const anchorNode = selection.anchorNode;
    const focusNode = selection.focusNode;
    // 检查选区是否在当前编辑器内
    if (
      editor.contains(anchorNode) ||
      editor === anchorNode ||
      editor.contains(focusNode) ||
      editor === focusNode
    ) {
      return selection;
    }
  }
  return null;
}
// 设置默认位置
export function setCursorPosition(data: any) {
  const position = data.position;
  if (!data.element || !window.getSelection) return;

  try {
    const sel = window.getSelection();
    if (!sel) return;

    // 检查目标元素是否仍在DOM中
    if (!document.contains(data.element)) {
      console.warn("Target element is no longer in DOM");
      return;
    }

    // 获取文本节点
    let targetNode = data.element.childNodes[0] || data.element;
    if (targetNode.nodeType !== Node.TEXT_NODE) {
      targetNode = targetNode.childNodes[0] || targetNode;
    }

    // 验证位置是否有效
    const maxOffset = targetNode.length || 0;
    const safePosition = Math.min(position, maxOffset);

    sel.collapse(targetNode, safePosition);
  } catch (error) {
    console.error("Cursor position restore failed:", error);
    // 失败时至少将光标放到元素末尾
    const sel = window.getSelection();
    sel?.collapse(data.element, 0);
  }
}
// 回复默认聚焦
export function safeRestoreCursor(element: any) {
  const sel = window.getSelection();
  if (!sel) return;

  // 尝试放到末尾
  const range = document.createRange();
  range.selectNodeContents(element);
  range.collapse(false); // 末尾
  sel.removeAllRanges();
  sel.addRange(range);
}
